package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.domain.LoginUser;
import com.sky.domain.User;
import com.sky.mapper.MenuMapper;
import com.sky.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果没有查询到用户
        if (user == null){
            throw new RuntimeException("用户名错误或者密码错误");
        }


//         select m.perms from sys_user_role ur
//         left join sys_role r on ur.role_id = r.id
//         left join sys_role_menu rm on ur.role_id = rm.role_id
//         left join sys_menu m on rm.menu_id = m.id
//         where ur.user_id = 3 and r.status = 0 and m.status = 0;
        // 查询对应的权限信息
        List<String> perms = menuMapper.selectPermsByUserId(user.getId().toString());

        // 封装成userdetails对象返回
        return new LoginUser(user,perms);
    }
}
